package com.ss.android.common.location;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Looper;
import android.os.Message;

import com.bytedance.common.b.UserAgentCompat;
import com.bytedance.common.plugin.interfaces.pushmanager.PushSettingManager;
import com.bytedance.common.utility.Logger;
import com.bytedance.common.utility.b.ThreadPlus;
import com.bytedance.common.utility.collection.WeakHandler;
import com.bytedance.common.utility.collection.WeakHandler.Callback;
import com.ss.android.common.util.NetworkUtils;
import com.ss.android.http.legacy.a.LegacyHeader;
import com.ss.android.newmedia.BaseApplication;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicInteger;

public final class LocationHelper implements LocationListener, Callback {
    public static final class c$a {
        private final BaseApplication a;

        public c$a(BaseApplication arg1) {
            this.a = arg1;
        }
    }

    final AtomicInteger a;
    private static long b = 600000;
    private static LocationHelper instance;
    private static c$a d = null;
    private final Context e;
    private final WeakHandler f;
    private final LocationGaoDeHelper g;
    private volatile long h;
    private volatile long i;
    private long j;
    private volatile boolean k;
    private Address l;

    private LocationHelper(Context arg3) {
        this.a = new AtomicInteger(0);
        this.e = arg3;
        this.l = new Address(Locale.getDefault());
        this.g = LocationGaoDeHelper.a(arg3);
        this.f = new WeakHandler(Looper.getMainLooper(), ((Callback) this));
    }

    public final void a() {
        this.g.a(false);
        this.a(false);
    }

    public static LocationHelper getInstance(Context context) {
        synchronized (LocationHelper.class) {
            if (instance == null) {
                instance = new LocationHelper(context.getApplicationContext());
            }
            return instance;
        }
    }

    public static void a(c$a arg0) {
        instance.d = arg0;
    }

    public static void a(int arg2) {
        if (arg2 > 300) {
            instance.b = ((long) (arg2 * 1000));
        }
    }

    @SuppressLint("MissingPermission")
    private Location a(Location arg9, boolean arg10, LocationManager arg11) {
        Location v1;
        boolean bingo = false;
        if (arg10) {
            try {
                if (arg11.isProviderEnabled("gps")) {
                    com.bytedance.common.b.a.a(arg11, "gps", ((LocationListener) this), Looper.getMainLooper());
                    this.f.sendEmptyMessageDelayed(1, 60000);
                } else {
                    bingo = true;
                }
            } catch (Exception v0) {
                Logger.d("LocationHelper", "request update error: " + v0);
            }
        } else {
            bingo = true;
        }

        if (bingo) {
            if (!arg11.isProviderEnabled("network")) {
            } else {
                com.bytedance.common.b.a.a(arg11, "network", ((LocationListener) this), Looper.getMainLooper());
                this.f.sendEmptyMessageDelayed(1, 60000);
            }
        }
        Iterator v2 = arg11.getProviders(true).iterator();
        do {
            if (v2.hasNext()) {
                Object v0_1 = v2.next();
                v1 = arg11.getLastKnownLocation(((String) v0_1));
                if (v1 == null) {
                    continue;
                }

                if (System.currentTimeMillis() - v1.getTime() > 432000000) {
                    continue;
                }

                if (Logger.debug()) {
                    Logger.d("LocationHelper", "location " + (((String) v0_1)) + " " + v1.toString());
                }

                if (arg9 != null && arg9.getTime() >= v1.getTime()) {
                    continue;
                }

                return v1;
            }

            return arg9;
        }
        while (true);
    }

    private static boolean a(double arg10, double arg12, double arg14, double arg16) {
        float[] v8 = new float[3];
        Location.distanceBetween(arg10, arg12, arg14, arg16, v8);
        boolean v0 = v8[0] < 10000f ? true : false;
        return v0;
    }

    private static boolean a(Address arg11, double arg12, double arg14) {
        boolean v0_2 = false;
        boolean v1_2 = false;
        String v8 = String.format("http://maps.googleapis.com/maps/api/geocode/json?latlng=%1$s,%2$s&sensor=true&language=zh-CN", String.valueOf(arg12), String.valueOf(arg14));
        String v1 = String.format("http://api.map.baidu.com/geocoder/v2/?output=json&location=%1$s,%2$s&ak=XYUPDnaR4Fp1LbU7GT2L7VIK", String.valueOf(arg12), String.valueOf(arg14));
        try {
            ArrayList v3 = new ArrayList();
            ((List) v3).add(new LegacyHeader("Referer", "http://nativeapp.toutiao.com"));
            String v0_1 = NetworkUtils.doGet(102400, v1, false, ((List) v3), null, null);
            if (arg11 == null) {
                v1_2 = false;
            } else if (!android.support.design.a.isTextEmpty(v0_1)) {
                JSONObject v1_1 = new JSONObject(v0_1);
                if (v1_1.optInt("status", -1) != 0) {
                    v1_2 = false;
                } else {
                    v1_1 = v1_1.optJSONObject("result").optJSONObject("addressComponent");
                    v0_1 = v1_1.optString("city");
                    if (android.support.design.a.isTextEmpty(v0_1)) {
                        v1_2 = false;
                    } else {
                        if (v0_1.endsWith("市")) {
                            v0_1 = v0_1.substring(0, v0_1.length() - 1);
                        }
                        arg11.setLocality(v0_1);
                        arg11.setAdminArea(v1_1.optString("province"));
                        v1_2 = true;
                    }
                }
            } else {
                v1_2 = false;
            }
            Logger.d("LocationHelper", "get city from baidu " + arg11.getLocality());
        } catch (Throwable v0) {
            Logger.d("LocationHelper", "get location from baidu error:" + v0);
        }

        if (v1_2) {
            v0_2 = true;
            return v0_2;
        }

        int v0_3 = 102400;
        try {
            v0_2 = instance.a(arg11, NetworkUtils.doGet(v0_3, v8, false));
            Logger.d("LocationHelper", "get city from google " + arg11.getLocality());
            return v0_2;
        } catch (Throwable v1_3) {
            Logger.d("LocationHelper", "get location from google error:" + v1_3);
            return v0_2;
        }


    }

    private static boolean a(Address arg12, String arg13) throws Exception {
        String v0 = null;
        boolean v4 = false;
        if (arg12 != null && !android.support.design.a.isTextEmpty(arg13)) {
            JSONArray v1 = new JSONObject(arg13).optJSONArray("results");
            if (v1 != null && v1.length() >= 0) {
                JSONArray v6 = v1.optJSONObject(0).optJSONArray("address_components");
                int v7 = v6.length();
                int v5 = 0;
                String v1_1 = v0;
                String v2 = v0;
                while (v5 < v7) {
                    JSONObject v8 = v6.optJSONObject(v5);
                    JSONArray v9 = v8.optJSONArray("types");
                    if (v9 != null && v9.length() > 0) {
                        int v3;
                        for (v3 = 0; v3 < v9.length(); ++v3) {
                            String v10 = v9.getString(v3);
                            if ("locality".equals(v10)) {
                                v2 = v8.optString("short_name");
                            } else if ("administrative_area_level_1".equals(v10)) {
                                v1_1 = v8.optString("short_name");
                            } else if ("country".equals(v10)) {
                                v0 = v8.optString("short_name");
                            }
                        }
                    }

                    ++v5;
                }

                if (android.support.design.a.isTextEmpty(v2)) {
                    return v4;
                }

                arg12.setLocality(v2);
                if (!android.support.design.a.isTextEmpty(v1_1)) {
                    arg12.setAdminArea(v1_1);
                }

                if (!android.support.design.a.isTextEmpty(v0)) {
                    arg12.setCountryCode(v0);
                }

                v4 = true;
            }
        }

        return v4;
    }

    public final void a(boolean arg7) {
        if (NetworkUtils.isNetworkAvailable(this.e)) {
            long v0 = System.currentTimeMillis();
            if (this.a.get() <= 0 && v0 - this.j >= 120000 && v0 - this.i >= instance.b) {
                this.a.incrementAndGet();
                this.j = v0;
                new ThreadPlus(new com.ss.android.common.location.d(this, arg7), "LocationHelperThread", true).start();
            }
        }
    }

    final void a(Location arg13, boolean arg14) {
        long v0_4;
        Address v8;
        Address v7;
        Object v0_1;
        try {
            this.loadSavedLocation();
            Logger.d("LocationHelper", "try to refresh location...");
            v0_1 = this.e.getSystemService(Context.LOCATION_SERVICE);
            if (arg13 == null) {
                arg13 = this.a(arg13, arg14, ((LocationManager) v0_1));
            }

            if (arg13 == null) {
                return;
            }

            double v2 = arg13.getLatitude();
            double v4 = arg13.getLongitude();
            v7 = new Address(Locale.getDefault());
            v7.setLatitude(v2);
            v7.setLongitude(v4);
            try {
                Iterator v1 = new Geocoder(this.e, Locale.CHINESE).getFromLocation(v2, v4, 2).iterator();
                do {
                    if (!v1.hasNext()) {
                        v8 = v7;
                        break;
                    }

                    v0_1 = v1.next();
                    if (!((Address) v0_1).hasLatitude()) {
                        continue;
                    }

                    if (((Address) v0_1).hasLongitude()) {
                        Logger.d("LocationHelper", "location refreshed: " + v0_1);
                        synchronized (this) {
                            this.l = ((Address) v0_1);
                            this.k = true;
                            this.i = System.currentTimeMillis();
                            if (arg13 != null) {
                                this.h = UserAgentCompat.getTime(arg13);
                            }
                            this.e();
                        }
                        v8 = null;
                        break;
                    }
                } while (true);
            } catch (Exception v0_2) {
                Logger.d("LocationHelper", "geocoder exception: " + v0_2);
                v8 = v7;
            }

            label_52:
            if (v8 == null) {
                return;
            }
            boolean v0_3;
            if (v8 != null) {
                try {
                    if (!v8.hasLatitude() || !v8.hasLongitude()) {
                        v0_3 = false;
                    } else {
                        v0_3 = instance.a(v8, v8.getLatitude(), v8.getLongitude());
                    }
                } catch (Throwable v0) {
                    Logger.d("LocationHelper", "Exception in doRefreshLocation: " + v0.toString());
                    return;
                }
            } else {
                v0_3 = false;
            }
            if ((v0_3) && v8 != null) {
                synchronized (this) {
                    this.l = v8;
                    this.k = true;
                    this.i = System.currentTimeMillis();
                    if (arg13 != null) {
                        this.h = UserAgentCompat.getTime(arg13);
                    }
                    this.e();
                }
                Logger.d("LocationHelper", "location city refreshed: " + v8.getLocality());
                return;
            }
            if (v8 == null) {
                return;
            }

            if (!v8.hasLatitude()) {
                return;
            }

            if (!v8.hasLongitude()) {
                return;
            }

            long v10 = System.currentTimeMillis();
            Address v2_1 = this.l;
            if (v2_1 != null && (instance.a(v2_1.getLatitude(), v2_1.getLongitude(), v8.getLatitude(), v8.getLongitude()))) {
                v0_4 = UserAgentCompat.getTime(arg13);
                if (v0_4 > this.i) {
                    this.i = v0_4;
                }

                if (v0_4 <= this.h) {
                    return;
                }

                this.h = v0_4;
                return;
            }

            if (v10 - this.i <= 10800000) {
                return;
            }

            Logger.d("LocationHelper", "location fixed: latitude/longitude only");
            synchronized (v8) {
                v0_4 = v10 - 300000;
                this.i = v0_4;
                this.h = UserAgentCompat.getTime(arg13);
                this.l = v8;
                this.k = true;
                this.e();
                return;
            }
        } catch (Throwable v0) {
            Logger.d("LocationHelper", "Exception in doRefreshLocation: " + v0.toString());
            return;
        }
    }

    public final boolean a(long arg6) {
        boolean v0 = this.i + instance.b >= arg6 ? true : false;
        return v0;
    }

    public final Address loadSavedLocation() {
        long v4_4;
        Address address;
        long v6_1;
        synchronized (this) {
            if (this.k) {
                Address v4_3 = this.l;
                if (v4_3 != null && (v4_3.hasLatitude()) && (v4_3.hasLongitude())) {
                    return v4_3;
                } else {
                    return null;
                }
            }

            this.k = true;
            SharedPreferences sharedPreferences = this.e.getSharedPreferences("ss_location", 0);
            try {
                String v5 = sharedPreferences.getString("latitude", null);
                String v6 = sharedPreferences.getString("longitude", null);
                if (!android.support.design.a.isTextEmpty(v5) && !android.support.design.a.isTextEmpty(v6)) {
                    double v8 = Double.parseDouble(v5);
                    double v10 = Double.parseDouble(v6);
                    v5 = sharedPreferences.getString("country_code", "");
                    String v12 = sharedPreferences.getString("admin_area", "");
                    String v13 = sharedPreferences.getString("locality", "");
                    String v14 = sharedPreferences.getString("country_name", "");
                    String v15 = sharedPreferences.getString("district", "");
                    String v16 = sharedPreferences.getString("address", "");
                    long v18 = sharedPreferences.getLong("fix_time", 0);
                    v6_1 = sharedPreferences.getLong("location_time", 0);
                    address = new Address(Locale.getDefault());
                    address.setLatitude(v8);
                    address.setLongitude(v10);
                    address.setCountryCode(v5);
                    address.setAdminArea(v12);
                    address.setLocality(v13);
                    address.setCountryName(v14);
                    address.setSubLocality(v15);
                    address.setThoroughfare(v16);
                    this.l = address;
                    v4_4 = System.currentTimeMillis();
                    this.i = v18;
                    if (this.i > v4_4) {
                        this.i = v4_4;
                    }

                    if (v6_1 <= v4_4) {
                        v4_4 = v6_1;
                    }
                    this.h = v4_4;
                    address = this.l;
                    if (address != null && (address.hasLatitude()) && (address.hasLongitude())) {
                        return address;
                    } else {
                        return null;
                    }
                }
                return null;
            } catch (Exception v4_2) {
                Logger.d("LocationHelper", "load saved location exception: " + v4_2);
                return null;
            }
        }
    }

    public final long getLocTime() {
        this.loadSavedLocation();
        long v2 = this.i;
        long v0 = this.h;
        if (v0 <= 0) {
            v0 = v2;
        }

        return v0;
    }

    public final JSONObject d() {
        JSONObject v0 = null;
        synchronized (this) {
            Address v2 = this.loadSavedLocation();
            if (v2 == null) {
                return v0;
            }

            if (!v2.hasLatitude()) {
                return v0;
            }

            if (!v2.hasLongitude()) {
                return v0;
            }

            if (System.currentTimeMillis() - this.i > 432000000) {
                return v0;
            }

            try {
                JSONObject v1_1 = new JSONObject();
                v1_1.put("latitude", v2.getLatitude());
                v1_1.put("longitude", v2.getLongitude());
                v1_1.put("country", v2.getCountryName());
                v1_1.put("province", v2.getAdminArea());
                v1_1.put("city", v2.getLocality());
                v1_1.put("district", v2.getSubLocality());
                v1_1.put("address", v2.getThoroughfare());
                long v2_1 = this.h;
                if (v2_1 <= 0) {
                    v2_1 = this.i;
                }

                v1_1.put("loc_time", v2_1);
                v0 = v1_1;
            } catch (Exception v1) {
            }
            return v0;
        }
    }

    private void e() {
        double v4;
        double v2;
        c$a v0_2;
        SharedPreferences.Editor v1 = this.e.getSharedPreferences("ss_location", 0).edit();
        v1.putString("latitude", String.valueOf(this.l.getLatitude()));
        v1.putString("longitude", String.valueOf(this.l.getLongitude()));
        String v0 = this.l.getCountryCode();
        if (v0 == null) {
            v0 = "";
        }

        v1.putString("country_code", v0);
        v0 = this.l.getAdminArea();
        if (v0 == null) {
            v0 = "";
        }

        v1.putString("admin_area", v0);
        v0 = this.l.getLocality();
        if (v0 == null) {
            v0 = "";
        }

        v1.putString("locality", v0);
        v0 = this.l.getCountryName();
        if (v0 == null) {
            v0 = "";
        }

        v1.putString("country_name", v0);
        v0 = this.l.getThoroughfare();
        if (v0 == null) {
            v0 = "";
        }

        v1.putString("address", v0);
        v0 = this.l.getSubLocality();
        if (v0 == null) {
            v0 = "";
        }

        v1.putString("district", v0);
        v1.putLong("fix_time", this.i);
        v1.putLong("location_time", this.h);
        v1.commit();
        try {
            v0_2 = instance.d;
            if (v0_2 == null) {
                return;
            }

            v2 = this.l.getLatitude();
            v4 = this.l.getLongitude();
        } catch (Exception v0_1) {
            return;
        }

        try {
            JSONObject v1_1 = new JSONObject();
            v1_1.put("lon", v4);
            v1_1.put("lat", v2);
            PushSettingManager.getInstance().notifyLoc(v0_2.a, v1_1.toString());
        } catch (Exception v0_1) {
        }
    }

    private void f() {
        try {
            ((LocationManager) this.e.getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
        } catch (Throwable v0) {
        }
    }

    public final void handleMsg(Message message) {
        switch (message.what) {
            case 1: {
                this.f();
                break;
            }
        }
    }

    public final void onLocationChanged(Location arg10) {
        try {
            this.f();
            if (arg10 == null) {
                return;
            }

            Logger.d("LocationHelper", "onLocationChanged: " + arg10);
            Address v8 = this.l;
            if (v8 != null && (v8.hasLatitude()) && (v8.hasLongitude()) && (instance.a(v8.getLatitude(), v8.getLongitude(), arg10.getLatitude(), arg10.getLongitude())) && v8.getLocality() != null) {
                return;
            }

            this.a.incrementAndGet();
            this.j = System.currentTimeMillis();
            new ThreadPlus(new com.ss.android.common.location.e(this, arg10), "localechange", true).start();
        } catch (Exception v0) {
        }
    }

    public final void onProviderDisabled(String arg1) {
        this.f();
    }

    public final void onProviderEnabled(String arg3) {
        Logger.d("LocationHelper", "onProviderEnabled");
    }

    public final void onStatusChanged(String arg1, int arg2, Bundle arg3) {
        this.f();
    }
}

